// 账户相关功能模块
const AccountModule = {
    // 同步账户
    syncAccount: async function(accountId) {
        const statusCell = $(`#account-status-${accountId}`);
        const syncButton = $(`#sync-btn-${accountId}`);

        if (statusCell.length) {
            statusCell.text('请求中...');
        }

        try {
            await Api.apiRequest(`/email-accounts/${accountId}/sync`, { method: 'POST' });
            layui.layer.msg('同步任务已提交，正在后台执行...', { icon: 1, time: 2000 });
            if (statusCell.length) {
                statusCell.text('同步中...');
            }
            // 简单的轮询来检查状态并刷新
            setTimeout(() => this.checkSyncStatus(accountId), 5000);
        } catch (error) {
            layui.layer.msg('提交同步任务失败: ' + (error.detail || error.message), { icon: 2 });
            if (statusCell.length) {
                statusCell.text('失败'); // 或者恢复之前的状态
            }
        }
    },

    // 检查同步状态
    checkSyncStatus: async function(accountId) {
        try {
            const account = await Api.apiRequest(`/email-accounts/${accountId}`);
            if (account.sync_status === 'syncing') {
                // 如果仍在同步，5秒后再次检查
                setTimeout(() => this.checkSyncStatus(accountId), 5000);
            } else {
                // 同步完成或失败，刷新当前邮件列表
                layui.layer.msg('同步完成，正在刷新列表...', { icon: 1 });
                App.loadAccountFolders(); // 刷新左侧文件夹列表
                // 刷新当前邮件列表
                if (EmailModule.currentAccountId == accountId) {
                    EmailModule.loadEmailList(EmailModule.currentFolder, EmailModule.currentAccountId);
                }
            }
        } catch (error) {
            console.error('检查同步状态失败:', error);
            // 出错时停止轮询
        }
    },

    // 删除账户
    deleteAccount: async function(accountId) {
        layer.confirm('确定要删除这个邮箱账户吗？', async function(index){
            try {
                await Api.apiRequest(`/email-accounts/${accountId}`, { method: 'DELETE' });
                layui.layer.msg('账户已删除', { icon: 1 });
                App.loadAccountFolders(); // Refresh the folder list
                // Potentially clear the view if the deleted account was active
                $('#email-list-container').html('<div class="placeholder">请选择邮件</div>');
                $('#email-detail-container').html('<div class="placeholder">请选择邮件以查看详情</div>');
            } catch (error) {
                layui.layer.msg('删除失败: ' + (error.detail || error.message), { icon: 2 });
            }
            layer.close(index);
        });
    },

    // 显示账户设置菜单
    showAccountSettings: async function(accountId, triggerElement) {
        const $accountItem = $(triggerElement).closest('.account-list-item');
        const wasSelected = $accountItem.hasClass('selected');
        
        // 在打开菜单前立即添加选中状态（如果之前是选中的）
        if (wasSelected) {
            $accountItem.addClass('selected');
        }
        
        // 获取账户信息以确定当前状态
        let account = null;
        try {
            account = await Api.apiRequest(`/email-accounts/${accountId}`);
        } catch (error) {
            console.error('获取账户信息失败:', error);
            // 如果获取失败，使用默认菜单
            account = { is_active: true };
        }
        
        // 根据账户状态动态生成菜单
        const menuData = [
            { title: '复制邮箱', id: 'copy' },
            { type: '-' },
            { title: '刷新文件夹', id: 'refresh' },
            { title: '创建文件夹', id: 'create_folder' },
            { title: '同步邮件', id: 'sync' },
            { type: '-' },
            { title: '修改配置', id: 'edit' },
            { title: '重命名', id: 'rename' },
            { type: '-' },
            { title: account.is_active ? '禁用邮箱' : '启用邮箱', id: 'toggle_status' },
            { type: '-' },
            { title: '删除邮箱', id: 'delete' }
        ];
        
        layui.dropdown.render({
            elem: triggerElement,
            show: true,
            data: menuData,
            click: function(data) {
                switch (data.id) {
                    case 'refresh':
                        App.refreshAccountFolders(accountId, triggerElement);
                        break;
                    case 'edit':
                        AccountModule.editAccountConfig(accountId);
                        break;
                    case 'sync':
                        AccountModule.syncAccount(accountId);
                        break;
                    case 'rename':
                        AccountModule.renameAccount(accountId);
                        break;
                    case 'create_folder':
                        AccountModule.createFolder(accountId);
                        break;
                    case 'copy':
                        AccountModule.copyEmailAddress(accountId);
                        break;
                    case 'toggle_status':
                        AccountModule.toggleAccountStatus(accountId);
                        break;
                    case 'delete':
                        AccountModule.deleteAccount(accountId);
                        break;
                }
            },
            ready: function() {
                // 菜单打开后，强制确保账户保持选中状态
                if (wasSelected) {
                    // 使用 setTimeout 确保在 layui 的内部处理之后执行
                    setTimeout(() => {
                        $accountItem.addClass('selected');
                    }, 0);
                }
            },
            // 菜单关闭时的回调
            done: function() {
                // 菜单关闭后，如果之前是选中的，确保选中状态保持
                if (wasSelected) {
                    $accountItem.addClass('selected');
                }
                // 无论如何关闭（点击项或外部），都清空标记
                App.config.currentOpenMenuAccountId = null;
            }
        });
    },

    // 复制邮箱地址
    copyEmailAddress: async function(accountId) {
        try {
            const account = await Api.apiRequest(`/email-accounts/${accountId}`);
            const email = account.email;

            // 尝试使用 Clipboard API
            if (navigator.clipboard && window.isSecureContext) {
                try {
                    await navigator.clipboard.writeText(email);
                    layui.layer.msg('邮箱地址已复制', { icon: 1 });
                    return;
                } catch (err) {
                    console.warn('Clipboard API 复制失败:', err);
                    // 失败后继续尝试 execCommand
                }
            }

            // 备用方案：使用 execCommand
            const textArea = document.createElement("textarea");
            textArea.value = email;
            textArea.style.position = "absolute";
            textArea.style.left = "-9999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    layui.layer.msg('邮箱地址已复制', { icon: 1 });
                } else {
                    throw new Error('execCommand returned false.');
                }
            } catch (err) {
                console.warn('execCommand 复制失败:', err);
                // 最终回退方案：弹窗手动复制
                const fallbackHtml = `
                    <div style="padding: 20px;">
                        <p style="margin-bottom: 10px;">自动复制失败，请手动复制：</p>
                        <input type="text" class="layui-input" id="manual-copy-input" value="${escapeHtml(email)}" readonly>
                        <p style="margin-top: 10px; font-size: 12px; color: #999;">请长按或全选复制</p>
                    </div>
                `;
                layer.open({
                    type: 1,
                    title: '复制邮箱地址',
                    content: fallbackHtml,
                    area: DeviceDetector.isMobile() ? ['90%', 'auto'] : ['400px', 'auto'],
                    shadeClose: true,
                    success: function(layero, index) {
                        const input = $('#manual-copy-input');
                        input.focus();
                        input.select();
                    }
                });
            } finally {
                document.body.removeChild(textArea);
            }
        } catch (error) {
            layui.layer.msg('获取邮箱地址失败', { icon: 2 });
        }
    },

    // 重命名账户
    renameAccount: async function(accountId) {
        try {
            const account = await Api.apiRequest(`/email-accounts/${accountId}`);
            layer.prompt({
                formType: 0,
                value: account.name,
                title: '重命名账户',
            }, async function(value, index){
                layer.close(index);
                // 重命名操作直接调用更新接口，不需要验证
                try {
                    await Api.apiRequest(`/email-accounts/${accountId}`, {
                        method: 'PUT',
                        body: JSON.stringify({ name: value })
                    });
                    layui.layer.msg('账户重命名成功', { icon: 1 });
                    App.loadAccountFolders();
                } catch (error) {
                    layui.layer.msg('重命名失败: ' + (error.detail || error.message), { icon: 2 });
                }
            });
        } catch (error) {
            layui.layer.msg('加载账户信息失败', { icon: 2 });
        }
    },

    // 修改账户配置
    editAccountConfig: async function(accountId) {
        try {
            const account = await Api.apiRequest(`/email-accounts/${accountId}`);
            this.showAccountModal(account);
        } catch (error) {
            layui.layer.msg('加载账户信息失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },

    // 显示账户配置弹窗（添加/编辑）
    showAccountModal: function(account = null) {
        const isEdit = !!account;

        // 服务商配置
        const providers = {
            'qq': { name: 'QQ 邮箱', imap_server: 'imap.qq.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.qq.com', smtp_port: 465, smtp_ssl: true },
            'aliyun': { name: '阿里云企业邮箱', imap_server: 'imap.qiye.aliyun.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.qiye.aliyun.com', smtp_port: 465, smtp_ssl: true },
            '163': { name: '163 网易邮箱', imap_server: 'imap.163.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.163.com', smtp_port: 465, smtp_ssl: true },
            '126': { name: '126 网易邮箱', imap_server: 'imap.126.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.126.com', smtp_port: 465, smtp_ssl: true },
            'sina': { name: 'Sina (新浪邮箱)', imap_server: 'imap.sina.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.sina.com', smtp_port: 465, smtp_ssl: true },
            'gmail': { name: 'Gmail (Google)', imap_server: 'imap.gmail.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.gmail.com', smtp_port: 465, smtp_ssl: true },
            'outlook': { name: 'Outlook/Hotmail', imap_server: 'outlook.office365.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.office365.com', smtp_port: 587, smtp_ssl: true },
            'yahoo': { name: 'Yahoo Mail', imap_server: 'imap.mail.yahoo.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.mail.yahoo.com', smtp_port: 465, smtp_ssl: true },
            'icloud': { name: 'iCloud Mail (Apple)', imap_server: 'imap.mail.me.com', imap_port: 993, imap_ssl: true, smtp_server: 'smtp.mail.me.com', smtp_port: 587, smtp_ssl: true },
            'custom': { name: '自定义' },
        };

        const formId = isEdit ? 'edit-account-form' : 'add-account-form';
        const formHtml = `
            <div style="padding: 20px;">
                <form class="layui-form account-config-form" id="${formId}" lay-filter="${formId}">
                    ${isEdit ? `<input type="hidden" name="id" value="${account.id}">` : ''}
                    ${!isEdit ? `
                    <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left: 0;">
                            <select name="provider" lay-filter="provider-select">
                                ${Object.keys(providers).map(key => `<option value="${key}">${providers[key].name}</option>`).join('')}
                            </select>
                        </div>
                    </div>
                    ` : ''}
                    <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left: 0;">
                            <input type="text" name="name" required lay-verify="required" placeholder=" " class="layui-input" value="${isEdit ? account.name : ''}" title="例如：个人邮箱">
                            <label class="form-label">邮箱名称</label>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left: 0;">
                            <input type="email" name="email" required lay-verify="required|email" placeholder=" " class="layui-input" value="${isEdit ? account.email : ''}" ${isEdit ? 'readonly' : ''} title="请输入邮箱地址">
                            <label class="form-label">邮箱地址</label>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left: 0;">
                            <input type="password" name="password" ${isEdit ? '' : 'required lay-verify="required"'} placeholder=" " class="layui-input" title="${isEdit ? '如需修改请填写新密码' : '请输入邮箱密码或授权码'}">
                            <label class="form-label">邮箱密码</label>
                            ${isEdit ? '<div class="layui-form-mid layui-word-aux" style="margin-left: 0; padding-left: 0; color: #999; font-size: 12px;">留空则不修改密码</div>' : ''}
                        </div>
                    </div>
                    <div id="custom-settings">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="margin-left: 0;">
                                <input type="text" name="imap_server" required lay-verify="required" placeholder=" " class="layui-input" value="${isEdit ? account.imap_server : ''}" title="如: imap.qiye.aliyun.com">
                                <label class="form-label">IMAP服务器</label>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-inline" style="width: 120px; margin-left: 0;">
                                <input type="number" name="imap_port" id="imap_port_${isEdit ? 'edit' : 'add'}" value="${isEdit ? account.imap_port : ''}" required lay-verify="required" placeholder=" " class="layui-input" title="IMAP端口">
                                <label class="form-label">IMAP端口</label>
                            </div>
                            <div class="layui-form-mid" style="padding: 0; margin-left: 10px; display: inline-flex; align-items: center;">
                                <input type="checkbox" name="imap_ssl" lay-skin="switch" lay-text="SSL|OFF" ${isEdit && account.imap_ssl ? 'checked' : ''} lay-filter="imap_ssl_filter_${isEdit ? 'edit' : 'add'}">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="margin-left: 0;">
                                <input type="text" name="smtp_server" required lay-verify="required" placeholder=" " class="layui-input" value="${isEdit ? account.smtp_server : ''}" title="如: smtp.qiye.aliyun.com">
                                <label class="form-label">SMTP服务器</label>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-inline" style="width: 120px; margin-left: 0;">
                                <input type="number" name="smtp_port" id="smtp_port_${isEdit ? 'edit' : 'add'}" value="${isEdit ? account.smtp_port : ''}" required lay-verify="required" placeholder=" " class="layui-input" title="SMTP端口">
                                <label class="form-label">SMTP端口</label>
                            </div>
                            <div class="layui-form-mid" style="padding: 0; margin-left: 10px; display: inline-flex; align-items: center;">
                                <input type="checkbox" name="smtp_ssl" lay-skin="switch" lay-text="SSL|OFF" ${isEdit && account.smtp_ssl ? 'checked' : ''} lay-filter="smtp_ssl_filter_${isEdit ? 'edit' : 'add'}">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block" style="margin-left: 0;">
                            <select name="proxy_id" lay-filter="proxy-select">
                                <option value="">无代理</option>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
        `;

        // 使用统一的设备检测决定弹窗尺寸
        let layerArea;

        if (DeviceDetector.isMobile()) {
            // 移动端：使用最大宽高
            layerArea = ['100%', '100%'];
        } else {
            // PC端和平板端：使用固定尺寸
            layerArea = ['550px', 'auto'];
        }

        layer.open({
            type: 1,
            title: isEdit ? '修改邮箱账户' : '添加邮箱账户',
            content: formHtml,
            area: layerArea,
            shadeClose: true,  // 允许点击遮罩层关闭
            closeBtn: 1,  // 显示右上角关闭按钮
            btn: [isEdit ? '保存修改' : '立即添加', '重置'],
            btnAlign: 'c',  // 按钮居中
            yes: function(index, layero) {
                // 点击保存/添加按钮
                const formData = layui.form.val(formId);
                if (isEdit) {
                    AccountModule.handleUpdateAccount(account.id, formData);
                } else {
                    AccountModule.handleAddAccount(formData);
                }
            },
            btn2: function(index, layero) {
                // 点击重置按钮
                if (isEdit) {
                    // 编辑模式：重新填充表单数据
                    $('input[name="name"]', layero).val(account.name);
                    $('input[name="password"]', layero).val('');
                    $('input[name="imap_server"]', layero).val(account.imap_server);
                    $('input[name="imap_port"]', layero).val(account.imap_port);
                    $('input[name="imap_ssl"]', layero).prop('checked', account.imap_ssl);
                    $('input[name="smtp_server"]', layero).val(account.smtp_server);
                    $('input[name="smtp_port"]', layero).val(account.smtp_port);
                    $('input[name="smtp_ssl"]', layero).prop('checked', account.smtp_ssl);
                    layui.form.render(null, formId);
                } else {
                    // 添加模式：重置表单
                    $(`#${formId}`)[0].reset();
                    const form = layui.form;
                    form.render(null, formId);
                    // 重新触发服务商选择，恢复默认值
                    setTimeout(() => {
                        form.val(formId, { provider: 'qq' });
                        const provider = providers['qq'];
                        $('input[name="imap_server"]', layero).val(provider.imap_server);
                        $('input[name="imap_port"]', layero).val(provider.imap_port);
                        $('input[name="imap_ssl"]', layero).prop('checked', provider.imap_ssl);
                        $('input[name="smtp_server"]', layero).val(provider.smtp_server);
                        $('input[name="smtp_port"]', layero).val(provider.smtp_port);
                        $('input[name="smtp_ssl"]', layero).prop('checked', provider.smtp_ssl);
                        $('#custom-settings').show();
                        form.render(null, formId);
                    }, 100);
                }
                return false;  // 阻止关闭
            },
            success: async function(layero, index){
                const form = layui.form;
                form.render(null, formId);

                // 加载代理列表
                try {
                    const proxies = await Api.apiRequest('/proxies');
                    const proxySelect = $('select[name="proxy_id"]', layero);
                    proxySelect.empty();
                    proxySelect.append('<option value="">无代理</option>');
                    proxies.forEach(proxy => {
                        const selected = isEdit && account.proxy_id === proxy.id ? 'selected' : '';
                        // 构建选项文本，包含延迟信息
                        let optionText = `${proxy.name} (${proxy.type}://${proxy.host}:${proxy.port})`;
                        if (proxy.latency) {
                            optionText += ` - ${proxy.latency}ms`;
                        }
                        proxySelect.append(`<option value="${proxy.id}" ${selected}>${optionText}</option>`);
                    });
                    form.render('select');
                } catch (error) {
                    console.error('加载代理列表失败:', error);
                }

                // 服务商选择事件（仅添加模式）
                if (!isEdit) {
                    form.on(`select(provider-select)`, function(data){
                        const provider = providers[data.value];
                        if (provider && data.value !== 'custom') {
                            $('input[name="imap_server"]').val(provider.imap_server);
                            $('input[name="imap_port"]').val(provider.imap_port);
                            $('input[name="imap_ssl"]').prop('checked', provider.imap_ssl);
                            $('input[name="smtp_server"]').val(provider.smtp_server);
                            $('input[name="smtp_port"]').val(provider.smtp_port);
                            $('input[name="smtp_ssl"]').prop('checked', provider.smtp_ssl);
                        }
                        $('#custom-settings').show();
                        form.render();
                    });

                    // 触发默认服务商选择
                    setTimeout(() => {
                        form.val(formId, { provider: 'qq' });
                        const provider = providers['qq'];
                        $('input[name="imap_server"]').val(provider.imap_server);
                        $('input[name="imap_port"]').val(provider.imap_port);
                        $('input[name="imap_ssl"]').prop('checked', provider.imap_ssl);
                        $('input[name="smtp_server"]').val(provider.smtp_server);
                        $('input[name="smtp_port"]').val(provider.smtp_port);
                        $('input[name="smtp_ssl"]').prop('checked', provider.smtp_ssl);
                        $('#custom-settings').show();
                        form.render();
                    }, 100);
                }

                // SSL开关事件（只在端口为空时自动填充）
                const filterSuffix = isEdit ? 'edit' : 'add';
                form.on(`switch(imap_ssl_filter_${filterSuffix})`, function(data){
                    const $port = $(`#imap_port_${filterSuffix}`);
                    if (!$port.val() || $port.val() === '') {
                        $port.val(data.elem.checked ? '993' : '143');
                    }
                });

                form.on(`switch(smtp_ssl_filter_${filterSuffix})`, function(data){
                    const $port = $(`#smtp_port_${filterSuffix}`);
                    if (!$port.val() || $port.val() === '') {
                        $port.val(data.elem.checked ? '465' : '25');
                    }
                });
            }
        });
    },

    // 处理更新账户
    handleUpdateAccount: async function(accountId, formData) {
        const accountData = {
            name: formData.name,
            email: formData.email, // 确保 email 字段被包含
            imap_server: formData.imap_server,
            imap_port: parseInt(formData.imap_port),
            imap_ssl: formData.imap_ssl === 'on',
            smtp_server: formData.smtp_server,
            smtp_port: parseInt(formData.smtp_port),
            smtp_ssl: formData.smtp_ssl === 'on',
            proxy_id: formData.proxy_id ? parseInt(formData.proxy_id) : null
        };

        // 如果用户输入了新密码，则包含密码字段
        if (formData.password) {
            accountData.password = formData.password;
        }

        try {
            // 在保存前进行验证
            await AccountModule.validateAndSave(accountData, accountId);
        } catch (error) {
            layui.layer.msg('更新失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },

    // 加载添加账户页面 (弹窗形式)
    loadAddAccount: function() {
        this.showAccountModal();
    },

    // 处理添加账户
    handleAddAccount: async function(formData) {
        const accountData = {
            name: formData.name,
            email: formData.email,
            password: formData.password,
            imap_server: formData.imap_server,
            imap_port: parseInt(formData.imap_port),
            imap_ssl: formData.imap_ssl === 'on',
            smtp_server: formData.smtp_server,
            smtp_port: parseInt(formData.smtp_port),
            smtp_ssl: formData.smtp_ssl === 'on',
            proxy_id: formData.proxy_id ? parseInt(formData.proxy_id) : null
        };

        try {
            // 在保存前进行验证
            await AccountModule.validateAndSave(accountData);
        } catch (error) {
            layui.layer.msg('添加失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },

    // 验证并保存账户信息
    validateAndSave: async function(accountData, accountId = null) {
        const loadingIndex = layui.layer.load(1, { shade: [0.1, '#fff'] });
        try {
            // 步骤1: 隐式验证配置
            await Api.apiRequest('/email-accounts/validate', {
                method: 'POST',
                body: JSON.stringify(accountData)
            });
            
            layui.layer.close(loadingIndex);

            // 步骤2: 验证成功后，执行添加或更新操作
            const url = accountId ? `/email-accounts/${accountId}` : '/email-accounts';
            const method = accountId ? 'PUT' : 'POST';
            
            await Api.apiRequest(url, {
                method: method,
                body: JSON.stringify(accountData)
            });

            layer.closeAll();
            layui.layer.msg(accountId ? '账户更新成功' : '邮箱账户添加成功', { icon: 1 });
            App.loadAccountFolders();

        } catch (error) {
            layui.layer.close(loadingIndex);
            layui.layer.msg('验证失败: ' + (error.detail || error.message), { icon: 2 });
            // 抛出错误以便上层调用捕获
            throw error;
        }
    },

    // 加载个人资料
    loadProfile: async function() {
        try {
            const user = await App.getCurrentUser();
            this.renderProfile(user);
        } catch (error) {
            layui.layer.msg('加载用户信息失败', { icon: 2 });
        }
    },

    // 渲染个人资料
    renderProfile: function(user) {
        const mfaEnabled = user.is_mfa_enabled;
        const formHtml = `
            <div style="padding: 20px;">
                <form class="layui-form" id="profile-form" lay-filter="profile-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">头像</label>
                        <div class="layui-input-block">
                            <div class="layui-upload">
                                <button type="button" class="layui-btn" id="upload-avatar-btn">上传图片</button>
                                <div class="layui-upload-list">
                                    <img class="layui-upload-img" id="avatar-preview" src="${user.avatar || 'images/user-avatar.png'}" style="width: 100px; height: 100px; border-radius: 50%;">
                                    <p id="upload-avatar-text"></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">全名</label>
                        <div class="layui-input-block">
                            <input type="text" name="full_name" value="${user.full_name || ''}" placeholder="选填" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">邮箱</label>
                        <div class="layui-input-block">
                            <input type="email" name="email" value="${user.email || ''}" placeholder="邮箱地址" class="layui-input" required lay-verify="required|email">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">新密码</label>
                        <div class="layui-input-block">
                            <input type="password" name="password" id="new-password-input" placeholder="不改请留空" class="layui-input" title="8位以上">
                        </div>
                    </div>
                    ${mfaEnabled ? `
                    <div class="layui-form-item" id="mfa-input-container" style="display: none;">
                        <label class="layui-form-label">MFA代码</label>
                        <div class="layui-input-block">
                            <input type="text" name="mfa_token" placeholder="请输入6位MFA代码" class="layui-input" maxlength="6">
                        </div>
                    </div>
                    ` : ''}
                </form>
            </div>
        `;

        // 使用统一的设备检测决定弹窗尺寸
        let layerArea;
        
        if (DeviceDetector.isMobile()) {
            // 移动端：使用最大宽高
            layerArea = ['100%', '100%'];
        } else {
            // PC端和平板端：使用固定尺寸
            layerArea = ['500px', 'auto'];
        }
        
        layer.open({
            type: 1,
            title: '个人资料',
            content: formHtml,
            area: layerArea,
            btn: ['保存', '取消'],
            shadeClose: true,
            btnAlign: 'c',
            yes: function(index, layero){
                const formData = layui.form.val('profile-form');
                AccountModule.handleUpdateProfile(formData);
            },
            success: function() {
                layui.form.render(null, 'profile-form');

                layui.upload.render({
                    elem: '#upload-avatar-btn',
                    url: Api.config.apiBaseUrl + '/upload?type=avatar',
                    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') },
                    accept: 'images',
                    acceptMime: 'image/jpeg, image/png, image/gif',
                    size: 2048, // 2MB
                    done: function(res){
                        if(res.success){
                            $('#avatar-preview').attr('src', res.data.avatar_url || res.data.url);
                            // 更新顶部导航栏头像
                            $('.layui-nav-img').attr('src', res.data.avatar_url || res.data.url);
                        } else {
                            layui.layer.msg(res.msg || '上传失败');
                        }
                    },
                    error: function(){
                        layui.layer.msg('请求异常');
                    }
                });

                if (mfaEnabled) {
                    const passwordInput = $('#new-password-input');
                    const mfaContainer = $('#mfa-input-container');
                    passwordInput.on('input', function() {
                        if ($(this).val()) {
                            mfaContainer.show();
                        } else {
                            mfaContainer.hide();
                        }
                    });
                }
            }
        });
    },

    // 显示MFA设置弹窗
    showSetupMfaModal: async function() {
        try {
            // 使用统一验证弹窗
            const verificationToken = await AccountModule.showVerificationModal({
                title: '绑定MFA - 身份验证'
            });
            
            // 验证成功后继续绑定流程
            const mfaData = await Api.apiRequest('/users/me/mfa/generate', { method: 'POST' });
                const setupHtml = `
                    <div style="padding: 20px; text-align: center;">
                        <p>请使用您的认证应用扫描下方的二维码：</p>
                        <img src="${mfaData.qr_code}" alt="MFA QR Code" style="width: 200px; height: 200px; margin: 15px 0;">
                        <p>或者手动输入密钥：</p>
                        <code>${mfaData.secret}</code>
                        <hr>
                        <p>扫描后，请输入应用生成的6位数字代码以完成绑定：</p>
                        <div class="layui-form-item">
                            <input type="text" id="mfa-token-input" class="layui-input" placeholder="6位数字代码" maxlength="6">
                        </div>
                    </div>
                `;
                layer.open({
                    type: 1,
                    title: '绑定MFA',
                    content: setupHtml,
                    area: ['400px', 'auto'],
                    btn: ['确认绑定', '取消'],
                    yes: async function(index, layero) {
                        const token = $('#mfa-token-input').val();
                        if (!/^\d{6}$/.test(token)) {
                            layer.msg('请输入6位数字代码', { icon: 2, time: 2000 });
                            // 注意：这里不重新打开，因为二维码弹窗还在，只是提示用户输入正确
                            return;
                        }
                        try {
                            await Api.apiRequest('/users/me/mfa/enable', {
                                method: 'POST',
                                body: JSON.stringify({ token: token })
                            });
                            layer.msg('MFA绑定成功', { icon: 1 }, function() {
                                layer.closeAll();
                                // 清除用户缓存，强制重新获取最新用户信息
                                Api.clearUserCache();
                                App.checkAuthStatus(); // 重新加载用户信息和UI
                            });
                        } catch (error) {
                            layer.msg('绑定失败: ' + (error.message || '未知错误'), { icon: 2, time: 2000 }, function() {
                                layer.closeAll(); // 关闭所有弹窗
                                AccountModule.showSetupMfaModal(); // 从头开始
                            });
                        }
                    }
                });
        } catch (error) {
            if (error.message !== '用户取消验证') {
                layer.msg('验证失败', { icon: 2, time: 2000 });
            }
        }
    },

    // 显示禁用MFA弹窗
    showDisableMfaModal: async function() {
        try {
            // 使用统一验证弹窗
            const verificationToken = await AccountModule.showVerificationModal({
                title: '解绑MFA - 身份验证'
            });
            
            // 注意：解绑MFA需要使用MFA代码验证，这里需要特殊处理
            // 因为统一验证弹窗已经验证了MFA，我们可以直接调用解绑接口
            // 但原接口需要token参数，需要修改后端或保持原有逻辑
            
            // 为保持兼容，这里仍然使用原有的prompt方式获取MFA代码
            layer.prompt({
                formType: 0,
                title: '请输入MFA代码以禁用',
                maxlength: 6
            }, async function(token, index){
                if (!/^\d{6}$/.test(token)) {
                    layer.close(index);
                    layer.msg('请输入6位数字代码', { icon: 2, time: 2000 });
                    return;
                }
                layer.close(index);
                try {
                    await Api.apiRequest('/users/me/mfa/disable', {
                        method: 'POST',
                        body: JSON.stringify({ token: token })
                    });
                    layer.msg('MFA已禁用', { icon: 1 }, function() {
                        layer.closeAll();
                        Api.clearUserCache();
                        App.checkAuthStatus();
                    });
                } catch (error) {
                    layer.msg('禁用失败: ' + (error.message || '未知错误'), { icon: 2, time: 2000 });
                }
            });
        } catch (error) {
            if (error.message !== '用户取消验证') {
                layer.msg('验证失败', { icon: 2, time: 2000 });
            }
        }
    },

    // 处理更新个人资料
    handleUpdateProfile: async function(formData) {
        const updateData = {
            full_name: formData.full_name?.trim() || '',
            email: formData.email?.trim() || ''
        };

        // 如果要修改密码，需要先进行验证
        if (formData.password) {
            try {
                // 使用统一验证弹窗
                const verificationToken = await AccountModule.showVerificationModal({
                    title: '修改密码 - 身份验证'
                });
                
                updateData.password = formData.password;
                updateData.verification_token = verificationToken;
                
                this.executeProfileUpdate(updateData);
            } catch (error) {
                if (error.message !== '用户取消验证') {
                    layui.layer.msg('验证失败', { icon: 2 });
                }
            }
        } else {
            // 不修改密码，直接更新
            this.executeProfileUpdate(updateData);
        }
    },

    executeProfileUpdate: async function(updateData) {
        try {
            await Api.apiRequest('/users/me', {
                method: 'PUT',
                body: JSON.stringify(updateData)
            });
            layui.layer.msg('个人资料更新成功', { icon: 1 }, function() {
                layer.closeAll('page');
                // 清除用户缓存并重新获取
                Api.clearUserCache();
                // 如果密码被修改，可能需要重新登录或刷新状态
                if (updateData.password) {
                    App.checkAuthStatus();
                }
            });
        } catch (error) {
            layui.layer.msg('更新失败: ' + (error.message || '未知错误'), { icon: 2 });
        }
    },

    // 创建文件夹
    createFolder: function(accountId, parentFolder = null) {
        layer.prompt({
            formType: 0,
            title: parentFolder ? `在 "${parentFolder}" 下创建子文件夹` : '创建新文件夹',
            value: ''
        }, async function(folderName, index) {
            folderName = folderName.trim();
            if (!folderName) {
                layer.msg('文件夹名称不能为空');
                return;
            }

            // 验证文件夹名称是否包含特殊符号
            const validFolderNameRegex = /^[a-zA-Z0-9\u4e00-\u9fa5\s_-]+$/;
            if (!validFolderNameRegex.test(folderName)) {
                layer.msg('文件夹名称不能包含特殊符号');
                return;
            }
            layer.close(index);

            // 显示loading
            const loadingIndex = layer.load(1, { shade: [0.3, '#fff'] });

            try {
                const requestBody = {
                    folder_name: String(folderName)
                };

                if (parentFolder) {
                    requestBody.parent_folder = String(parentFolder);
                }

                await Api.apiRequest(`/email-accounts/${accountId}/folders`, {
                    method: 'POST',
                    body: JSON.stringify(requestBody)
                });
                layer.close(loadingIndex);
                layer.msg('文件夹创建成功', { icon: 1 });
                // 只刷新当前账户的文件夹列表
                App.refreshAccountFolders(accountId, null);
                
                // 通过WebSocket请求后端刷新未读数
                if (App.ws && App.ws.readyState === WebSocket.OPEN) {
                    App.ws.send(JSON.stringify({
                        action: 'refresh_unread_counts'
                    }));
                }
            } catch (error) {
                layer.close(loadingIndex);
                layer.msg('创建文件夹失败: ' + (error.message || '未知错误'), { icon: 2 });
            }
        });
    },

    // 重命名文件夹
    renameFolder: function(accountId, folderName) {
        // 确保 folderName 是字符串类型，以防传入的是数字
        folderName = String(folderName);
        const parts = folderName.split('/');
        const currentName = parts[parts.length - 1];

        layer.prompt({
            formType: 0,
            title: `重命名文件夹 "${currentName}"`,
            value: currentName
        }, async function(newFolderName, index) {
            newFolderName = newFolderName.trim();
            if (!newFolderName) {
                layer.msg('文件夹名称不能为空');
                return;
            }
            
            // 验证文件夹名称是否包含特殊符号
            const validFolderNameRegex = /^[a-zA-Z0-9\u4e00-\u9fa5\s_-]+$/;
            if (!validFolderNameRegex.test(newFolderName)) {
                layer.msg('文件夹名称不能包含特殊符号');
                return;
            }

            if (newFolderName === currentName) { // Compare with just the name part
                layer.close(index);
                return;
            }
            layer.close(index);

            // 显示loading
            const loadingIndex = layer.load(1, { shade: [0.3, '#fff'] });

            const parentPath = parts.slice(0, -1).join('/');
            const newFullName = parentPath ? `${parentPath}/${newFolderName}` : newFolderName;

            try {
                await Api.apiRequest(`/email-accounts/${accountId}/folders`, {
                    method: 'PUT',
                    body: JSON.stringify({
                        old_dir: String(folderName),
                        new_dir: String(newFullName)
                    })
                });
                layer.close(loadingIndex);
                layer.msg('文件夹重命名成功', { icon: 1 });
                // 只刷新当前账户的文件夹列表
                App.refreshAccountFolders(accountId, newFullName, null);
                
                // 通过WebSocket请求后端刷新未读数
                if (App.ws && App.ws.readyState === WebSocket.OPEN) {
                    App.ws.send(JSON.stringify({
                        action: 'refresh_unread_counts'
                    }));
                }
            } catch (error) {
                layer.close(loadingIndex);
                layer.msg('重命名失败: ' + (error.message || '未知错误'), { icon: 2 });
            }
        });
    },

    // 显示绑定WebAuthn密钥弹窗
    showBindWebAuthnModal: async function() {
        // 检查浏览器支持
        if (!window.PublicKeyCredential) {
            layer.msg('您的浏览器不支持硬件密钥功能', { icon: 2 });
            return;
        }

        try {
            // 使用统一验证弹窗
            const verificationToken = await AccountModule.showVerificationModal({
                title: '绑定硬件密钥 - 身份验证'
            });
            
            // 验证成功，开始注册WebAuthn
            AccountModule.startWebAuthnRegistration();
        } catch (error) {
            if (error.message !== '用户取消验证') {
                layer.msg('验证失败', { icon: 2, time: 2000 });
            }
        }
    },

    // 开始WebAuthn注册流程
    startWebAuthnRegistration: async function() {
        const loadingIndex = layer.load(1, { shade: [0.3, '#fff'] });

        try {
            // 1. 请求注册选项
            const beginData = await Api.apiRequest('/webauthn/register/begin', {
                method: 'POST'
            });

            layer.close(loadingIndex);

            const options = beginData.options;

            // 2. 转换Base64URL为ArrayBuffer
            options.challenge = AuthModule.base64urlToBuffer(options.challenge);
            options.user.id = AuthModule.base64urlToBuffer(options.user.id);

            // 3. 调用浏览器WebAuthn API
            layer.msg('请按照提示操作您的安全密钥...', { icon: 16, time: 0, shade: 0.3 });
            
            const credential = await navigator.credentials.create({
                publicKey: options
            });

            layer.closeAll('dialog');

            // 4. 转换凭证为可传输格式
            const credentialForServer = {
                id: credential.id,
                rawId: AuthModule.bufferToBase64url(credential.rawId),
                type: credential.type,
                response: {
                    attestationObject: AuthModule.bufferToBase64url(credential.response.attestationObject),
                    clientDataJSON: AuthModule.bufferToBase64url(credential.response.clientDataJSON)
                }
            };

            // 5. 完成注册
            const loadingIndex2 = layer.load(1, { shade: [0.3, '#fff'] });
            await Api.apiRequest('/webauthn/register/complete', {
                method: 'POST',
                body: JSON.stringify({
                    credential: credentialForServer
                })
            });
            layer.close(loadingIndex2);

            layer.msg('硬件密钥绑定成功', { icon: 1 }, function() {
                // 清除用户缓存并重新加载
                Api.clearUserCache();
                App.checkAuthStatus();
            });

        } catch (error) {
            layer.close(loadingIndex);
            layer.closeAll('dialog');
            console.error('WebAuthn注册失败:', error);
            
            let errorMsg = '绑定硬件密钥失败';
            if (error.name === 'NotAllowedError') {
                errorMsg = '您取消了密钥注册';
            } else if (error.message) {
                errorMsg = error.message;
            } else if (error.detail) {
                errorMsg = error.detail;
            }
            
            layer.msg(errorMsg, { icon: 2, time: 3000 });
        }
    },

    // 显示解绑WebAuthn密钥弹窗
    showUnbindWebAuthnModal: async function() {
        try {
            // 使用统一验证弹窗
            const verificationToken = await AccountModule.showVerificationModal({
                title: '解绑硬件密钥 - 身份验证'
            });
            
            // 验证成功后解绑
            const loadingIndex = layer.load(1, { shade: [0.3, '#fff'] });
            
            await Api.apiRequest('/webauthn/unbind', {
                method: 'POST',
                body: JSON.stringify({ verification_token: verificationToken })
            });
            
            layer.close(loadingIndex);
            layer.msg('硬件密钥已解绑', { icon: 1 }, function() {
                Api.clearUserCache();
                App.checkAuthStatus();
            });
        } catch (error) {
            if (error.message !== '用户取消验证') {
                layer.msg(error.message || error.detail || '解绑失败', { icon: 2, time: 2000 });
            }
        }
    },

    /**
     * 统一验证弹窗
     * @param {Object} options - 配置选项
     * @param {Function} options.onSuccess - 验证成功回调，参数为 verification_token
     * @param {String} options.title - 弹窗标题，默认为"身份验证"
     * @returns {Promise<string>} - 返回verification_token
     */
    showVerificationModal: function(options = {}) {
        return new Promise(async (resolve, reject) => {
            const currentUser = App.config.currentUser;
            const title = options.title || '身份验证';
            
            // 构建Tab内容
            const tabs = [];
            let defaultTab = 'password'; // 默认Tab
            
            // 1. 密码验证（保底，总是显示）
            tabs.push({
                id: 'password',
                title: '<i class="layui-icon layui-icon-password"></i> 密码',
                content: `
                    <div class="verification-tab-content" style="padding: 20px;">
                        <div class="layui-form-item">
                            <label class="layui-form-label">密码</label>
                            <div class="layui-input-block">
                                <input type="password" id="verify-password-input" class="layui-input" placeholder="请输入当前密码" autocomplete="current-password">
                            </div>
                        </div>
                    </div>
                `
            });
            
            // 2. MFA验证（如已启用）
            if (currentUser.is_mfa_enabled) {
                tabs.push({
                    id: 'mfa',
                    title: '<i class="layui-icon layui-icon-cellphone"></i> MFA',
                    content: `
                        <div class="verification-tab-content" style="padding: 20px;">
                            <div class="layui-form-item">
                                <label class="layui-form-label">MFA代码</label>
                                <div class="layui-input-block">
                                    <input type="text" id="verify-mfa-input" class="layui-input" placeholder="请输入6位MFA代码" maxlength="6" autocomplete="one-time-code">
                                </div>
                            </div>
                        </div>
                    `
                });
                defaultTab = 'mfa'; // 如果有MFA，优先使用MFA
            }
            
            // 注意：WebAuthn验证需要复杂的challenge流程，不适合在统一验证弹窗中实现
            // 解绑密钥时使用密码或MFA验证即可
            
            // 构建Tab HTML
            const tabHtml = `
                <div class="layui-tab layui-tab-brief" lay-filter="verification-tabs">
                    <ul class="layui-tab-title">
                        ${tabs.map((tab, index) => `
                            <li ${tab.id === defaultTab ? 'class="layui-this"' : ''} lay-id="${tab.id}">${tab.title}</li>
                        `).join('')}
                    </ul>
                    <div class="layui-tab-content">
                        ${tabs.map((tab, index) => `
                            <div class="layui-tab-item ${tab.id === defaultTab ? 'layui-show' : ''}">${tab.content}</div>
                        `).join('')}
                    </div>
                </div>
            `;
            
            // 使用统一的设备检测决定弹窗尺寸
            let layerArea = DeviceDetector.isMobile() ? ['90%', 'auto'] : ['450px', 'auto'];
            
            const layerIndex = layer.open({
                type: 1,
                title: title,
                content: tabHtml,
                area: layerArea,
                btn: ['验证', '取消'],
                btnAlign: 'c',
                shadeClose: false,
                yes: async function(index, layero) {
                    // 获取当前激活的Tab
                    const activeTab = $('.layui-tab-title li.layui-this', layero).attr('lay-id');
                    await AccountModule.handleVerification(activeTab, layero, resolve, reject, index);
                },
                btn2: function(index) {
                    reject(new Error('用户取消验证'));
                    return true;
                },
                success: function(layero, index) {
                    // 初始化Tab
                    layui.element.render('tab');
                    
                    // 监听Tab切换
                    layui.element.on('tab(verification-tabs)', function(data){
                        const tabId = $(this).attr('lay-id');
                        // 清空其他Tab的输入
                        if (tabId !== 'password') $('#verify-password-input', layero).val('');
                        if (tabId !== 'mfa') $('#verify-mfa-input', layero).val('');
                    });
                    
                    // 为密码和MFA输入框添加回车监听
                    $('#verify-password-input, #verify-mfa-input', layero).on('keypress', function(e) {
                        if (e.which === 13) {
                            $('.layui-layer-btn0', layero).click();
                        }
                    });
                    
                    // 自动聚焦到默认Tab的输入框
                    setTimeout(() => {
                        if (defaultTab === 'password') {
                            $('#verify-password-input', layero).focus();
                        } else if (defaultTab === 'mfa') {
                            $('#verify-mfa-input', layero).focus();
                        }
                    }, 100);
                }
            });
        });
    },
    
    /**
     * 处理验证逻辑
     */
    handleVerification: async function(method, layero, resolve, reject, layerIndex) {
        let loadingIndex = null;
        try {
            let requestData = { method: method };
            
            if (method === 'password') {
                const password = $('#verify-password-input', layero).val();
                if (!password) {
                    layer.msg('请输入密码', { icon: 2 });
                    return;
                }
                requestData.password = password;
            } else if (method === 'mfa') {
                const mfaToken = $('#verify-mfa-input', layero).val();
                if (!mfaToken || !/^\d{6}$/.test(mfaToken)) {
                    layer.msg('请输入6位MFA代码', { icon: 2 });
                    return;
                }
                requestData.mfa_token = mfaToken;
            }
            
            // 调用统一验证接口
            loadingIndex = layer.load(1, { shade: [0.3, '#fff'] });
            const result = await Api.apiRequest('/auth/verify-unified', {
                method: 'POST',
                body: JSON.stringify(requestData)
            });
            layer.close(loadingIndex);
            loadingIndex = null;
            
            if (result && result.verification_token) {
                layer.close(layerIndex);
                layer.msg('验证成功', { icon: 1, time: 1000 });
                resolve(result.verification_token);
            } else {
                layer.msg('验证失败', { icon: 2 });
            }
        } catch (error) {
            // 确保关闭loading遮罩层
            if (loadingIndex !== null) {
                layer.close(loadingIndex);
            }
            layer.msg(error.message || error.detail || '验证失败', { icon: 2 });
        }
    },

    // 切换账户启用/禁用状态
    toggleAccountStatus: async function(accountId) {
        try {
            // 获取当前账户信息
            const account = await Api.apiRequest(`/email-accounts/${accountId}`);
            const currentStatus = account.is_active;
            const actionText = currentStatus ? '禁用' : '启用';
            
            // 确认对话框
            layer.confirm(`确定要${actionText}邮箱账户"${account.name || account.email}"吗？`, {
                title: `${actionText}邮箱账户`,
                icon: 3
            }, async (index) => {
                layer.close(index);
                
                // 显示loading
                const loadingIndex = layer.load(1, { shade: [0.3, '#fff'] });
                
                try {
                    // 调用后端接口切换状态
                    const result = await Api.apiRequest(`/email-accounts/${accountId}/status`, {
                        method: 'PUT'
                    });
                    
                    layer.close(loadingIndex);
                    
                    // 显示成功消息
                    layer.msg(result.msg || `邮箱账户已${actionText}`, { icon: 1 });
                    
                    // 更新禁用图标显示状态
                    const $accountItem = $(`.account-list-item[data-account-id="${accountId}"]`);
                    const $accountName = $accountItem.find('.account-name');
                    const $disabledIcon = $accountName.find('.layui-icon-disabled');
                    
                    if (currentStatus) {
                        // 当前是启用状态，操作是禁用
                        if ($disabledIcon.length === 0) {
                            $accountName.append('<i class="layui-icon layui-icon-disabled" style="color: #4f4f4f; font-size: 14px; margin-left: 5px;" title="已禁用"></i>');
                        }
                    } else {
                        // 当前是禁用状态，操作是启用
                        $disabledIcon.remove();
                    }
                    
                    // 重新加载账户文件夹列表以更新UI
                    App.loadAccountFolders();
                    
                    // 通过WebSocket请求后端刷新未读数和同步状态
                    if (App.ws && App.ws.readyState === WebSocket.OPEN) {
                        App.ws.send(JSON.stringify({
                            action: 'refresh_unread_counts'
                        }));
                        App.ws.send(JSON.stringify({
                            action: 'refresh_sync_failed'
                        }));
                    }
                    
                } catch (error) {
                    layer.close(loadingIndex);
                    layer.msg(`${actionText}失败: ` + (error.detail || error.message), { icon: 2 });
                }
            });
        } catch (error) {
            layer.msg('获取账户信息失败: ' + (error.detail || error.message), { icon: 2 });
        }
    },
    
};
